<?php

namespace app\admin\controller;

use app\admin\model\Crontab;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 优惠券
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{

    /**
     * Coupon模型对象
     * @var \app\admin\model\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Coupon;
        $this->view->assign("typeList", $this->model->getTypeList());

        $this->model::event('before_insert', function ($row){return $this->beforeSave($row);});
        $this->model::event('before_update', function ($row){return $this->beforeSave($row);});
    }

    // 处理前端输入的城市，分为三段存储
    protected function beforeSave($row){
        if(in_array($this->request->action(),['add','edit'])){

            if ($row->type=='goods'){
                if (empty($row->goods_id)){
                    exception('请选择赠送商品');
                    return false;
                }

            }
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('goods')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost()) {
           // $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                $params['status'] = 1;

                $res = $this->model->create($params);

                if ($params['validity_type'] == 0) {
                    $end_time = strtotime($params['end_time']);
                    $coupon_id = $res->id;
                    $cron = new Crontab();
                    $cron->setAttr('type','url');
                    $cron->title = '优惠券活动定时结束,id:'.$coupon_id;
                    $cron->content = request()->domain().'/api/coupon/expired?id='.$coupon_id;
                    $cron->schedule = schedule($end_time);
                    $cron->maximums = 1;
                    $cron->begintime = time();
                    $cron->endtime = $end_time;
                    $cron->status = 'normal';
                    $cron->save();
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a", [], 'strip_tags');

            if ($params) {
                Db::startTrans();
                try {
                    $row->save($params);

                    $coupon_id = $row->id;

                    Crontab::destroy(['title'=>'优惠券活动定时结束,id:'.$coupon_id]);
                    if ($params['validity_type'] == 0) {
                        $end_time = strtotime($params['end_time']);

                        $cron = new Crontab();
                        $cron->setAttr('type','url');
                        $cron->title = '优惠券活动定时结束,id:'.$coupon_id;
                        $cron->content = request()->domain().'/api/coupon/expired?id='.$coupon_id;
                        $cron->schedule = schedule($end_time);
                        $cron->maximums = 1;
                        $cron->begintime = time();
                        $cron->endtime = $end_time;
                        $cron->status = 'normal';
                        $cron->save();
                    }
                    Db::commit();
                    $this->success();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error();
            return;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
